<template>
  <div class="login-container">
    <!-- 背景装饰 -->
    <div class="background-decoration">
      <div class="decoration-circle circle-1"></div>
      <div class="decoration-circle circle-2"></div>
      <div class="decoration-circle circle-3"></div>
    </div>

    <!-- 登录卡片 -->
    <el-card class="login-card" shadow="always">
      <template #header>
        <div class="card-header">
          <div class="logo-section">
            <el-icon class="logo-icon" :size="48"><LocationFilled /></el-icon>
            <h1 class="title">南昌旅游规划系统</h1>
            <p class="subtitle">欢迎回来，请登录您的账户</p>
          </div>
        </div>
      </template>

      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="0"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="form.username"
            placeholder="请输入用户名"
            size="large"
            :prefix-icon="User"
            clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
            size="large"
            :prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <el-form-item>
          <div class="form-options">
            <el-checkbox v-model="rememberMe">记住我</el-checkbox>
            <el-link type="primary" :underline="false" class="forgot-password">
              忘记密码？
            </el-link>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleLogin"
            :loading="loading"
            size="large"
            class="login-button"
            :icon="loading ? null : Right"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>

        <el-form-item>
          <div class="register-link">
            <span>还没有账户？</span>
            <el-link type="primary" :underline="false" @click="goToRegister">
              立即注册
            </el-link>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 底部信息 -->
    <div class="footer-info">
      <p>© 2024 南昌旅游规划系统. All rights reserved.</p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { User, Lock, Right, LocationFilled } from '@element-plus/icons-vue'
import logger from '../utils/logger'

const router = useRouter()
const route = useRoute()
const store = useStore()

const formRef = ref(null)
const loading = ref(false)
const rememberMe = ref(false)

const form = reactive({
  username: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请填写完整的登录信息')
      return
    }

    loading.value = true

    try {
      const result = await store.dispatch('login', {
        username: form.username,
        password: form.password
      })

      if (result.success) {
        ElMessage.success('登录成功！')

        // 如果设置了记住我，保存用户名到本地存储
        if (rememberMe.value) {
          localStorage.setItem('remembered_username', form.username)
        } else {
          localStorage.removeItem('remembered_username')
        }

        // 根据角色跳转到不同页面
        const isAdmin = store.getters.isAdmin
        let redirect = route.query.redirect
        
        // 如果没有指定跳转页面，根据角色决定
        if (!redirect) {
          if (isAdmin) {
            redirect = '/admin'  // 管理员跳转到管理后台
          } else {
            redirect = '/dashboard'  // 普通用户跳转到个人空间
          }
        }
        
        // 如果管理员访问普通用户页面，跳转到管理后台
        if (isAdmin && redirect.startsWith('/dashboard')) {
          redirect = '/admin'
        }
        router.push(redirect)
      } else {
        ElMessage.error(result.error || '登录失败，请检查用户名和密码')
      }
    } catch (error) {
      logger.error('登录错误:', error)
      ElMessage.error('登录失败，请稍后重试')
    } finally {
      loading.value = false
    }
  })
}

const goToRegister = () => {
  router.push('/register')
}

// 页面加载时检查是否有记住的用户名
onMounted(() => {
  const rememberedUsername = localStorage.getItem('remembered_username')
  if (rememberedUsername) {
    form.username = rememberedUsername
    rememberMe.value = true
  }
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  /* 南昌旅游特色：天空蓝到水蓝渐变 */
  background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 50%, #90CAF9 100%);
  padding: 20px;
  overflow: hidden;
}

/* 背景装饰 */
.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 0;
}

.decoration-circle {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 20s infinite ease-in-out;
}

.circle-1 {
  width: 300px;
  height: 300px;
  top: -100px;
  left: -100px;
  animation-delay: 0s;
}

.circle-2 {
  width: 200px;
  height: 200px;
  top: 50%;
  right: -50px;
  animation-delay: 5s;
}

.circle-3 {
  width: 150px;
  height: 150px;
  bottom: -50px;
  left: 20%;
  animation-delay: 10s;
}

@keyframes float {
  0%, 100% {
    transform: translate(0, 0) scale(1);
    opacity: 0.3;
  }
  50% {
    transform: translate(30px, -30px) scale(1.1);
    opacity: 0.5;
  }
}

/* 登录卡片 */
.login-card {
  width: 100%;
  max-width: 450px;
  border-radius: 20px;
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  position: relative;
  z-index: 1;
  border: none;
}

.login-card :deep(.el-card__header) {
  padding: 40px 40px 20px;
  border-bottom: none;
  /* 南昌红到滕王阁金渐变 */
  background: linear-gradient(135deg, #C8102E 0%, #D4AF37 100%);
  border-radius: 20px 20px 0 0;
}

.login-card :deep(.el-card__body) {
  padding: 40px;
}

.card-header {
  text-align: center;
}

.logo-section {
  color: white;
}

.logo-icon {
  margin-bottom: 15px;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
}

.title {
  font-size: 28px;
  font-weight: 700;
  margin: 0 0 10px 0;
  color: white;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

.subtitle {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  margin: 0;
  font-weight: 300;
}

/* 表单样式 */
.login-form {
  margin-top: 20px;
}

.login-form :deep(.el-form-item) {
  margin-bottom: 25px;
}

.login-form :deep(.el-input__wrapper) {
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.login-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.login-form :deep(.el-input.is-focus .el-input__wrapper) {
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.forgot-password {
  font-size: 14px;
}

.login-button {
  width: 100%;
  height: 50px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 10px;
  /* 南昌红到滕王阁金渐变 */
  background: linear-gradient(135deg, #C8102E 0%, #D4AF37 100%);
  border: none;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(200, 16, 46, 0.4);
}

.login-button:hover {
  transform: translateY(-2px);
  background: linear-gradient(135deg, #D91E36 0%, #E6C866 100%);
  box-shadow: 0 6px 20px rgba(212, 175, 55, 0.5);
}

.login-button:active {
  transform: translateY(0);
}

.register-link {
  text-align: center;
  width: 100%;
  font-size: 14px;
  color: #666;
}

.register-link .el-link {
  font-weight: 600;
  margin-left: 5px;
}

/* 底部信息 */
.footer-info {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1;
  color: rgba(255, 255, 255, 0.8);
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-card {
    max-width: 100%;
    margin: 20px;
  }

  .login-card :deep(.el-card__header) {
    padding: 30px 20px 15px;
  }

  .login-card :deep(.el-card__body) {
    padding: 30px 20px;
  }

  .title {
    font-size: 24px;
  }

  .subtitle {
    font-size: 13px;
  }
}

/* 深色模式支持 */
@media (prefers-color-scheme: dark) {
  .login-card {
    background: rgba(30, 30, 30, 0.95);
  }

  .register-link {
    color: #ccc;
  }
}
</style>
